/**
 * 连连看游戏核心引擎
 */

// 游戏配置
const GAME_CONFIG = {
    easy: { rows: 6, cols: 8, timeLimit: null, baseScore: 10, tiles: ['🍎', '🍊', '🍋', '🍌', '🍉', '🍇', '🍓', '🥝', '🍑', '🍒', '🥥', '🍍'] },
    normal: { rows: 8, cols: 10, timeLimit: 30, baseScore: 12, tiles: ['🍎', '🍊', '🍋', '🍌', '🍉', '🍇', '🍓', '🥝', '🍑', '🍒', '🥥', '🍍', '🥭', '🍈', '🫐', '🍐', '🥑', '🍏'] },
    hard: { rows: 10, cols: 12, timeLimit: 20, baseScore: 15, tiles: ['🍎', '🍊', '🍋', '🍌', '🍉', '🍇', '🍓', '🥝', '🍑', '🍒', '🥥', '🍍', '🥭', '🍈', '🫐', '🍐', '🥑', '🍏', '🍅', '🫑', '🌽', '🥕', '🥔', '🍠'] }
};

// 游戏状态
let gameState = {
    board: [],
    config: null,
    score: 0,
    combo: 0,
    maxCombo: 0,
    pairsCleared: 0,
    totalPairs: 0,
    timeRemaining: 0,
    selectedTile: null,
    isPaused: false,
    isGameOver: false,
    timer: null,
    startTime: null,
    itemsUsed: [],
    userItems: {} // 用户道具数量
};

/**
 * 初始化游戏
 */
function initGame() {
    gameState.config = GAME_CONFIG[GAME_MODE];
    gameState.timeRemaining = gameState.config.timeLimit || 0; // 简单模式从0开始累加
    gameState.score = 0;
    gameState.combo = 0;
    gameState.maxCombo = 0;
    gameState.pairsCleared = 0;
    gameState.selectedTile = null;
    gameState.isPaused = false;
    gameState.isGameOver = false;
    gameState.startTime = Date.now();
    gameState.itemsUsed = [];
    
    // 加载用户道具
    loadUserItems();
    
    // 生成棋盘
    generateBoard();
    
    // 渲染棋盘
    renderBoard();
    
    // 启动计时器
    startTimer();
    
    // 更新显示
    updateDisplay();
}

/**
 * 加载用户道具数量
 */
function loadUserItems() {
    fetch('/user/game/items')
        .then(response => response.json())
        .then(data => {
            if (data.code === 200) {
                gameState.userItems = data.data || {};
                updateToolButtons();
            }
        })
        .catch(error => {
            console.error('加载道具失败', error);
        });
}

/**
 * 生成棋盘
 */
function generateBoard() {
    const { rows, cols, tiles } = gameState.config;
    const totalTiles = rows * cols;
    
    // 确保是偶数
    const pairCount = Math.floor(totalTiles / 2);
    gameState.totalPairs = pairCount;
    
    // 生成配对的图标
    let iconArray = [];
    for (let i = 0; i < pairCount; i++) {
        const icon = tiles[i % tiles.length];
        iconArray.push(icon, icon);
    }
    
    // 打乱数组
    iconArray = shuffleArray(iconArray);
    
    // 生成二维数组
    gameState.board = [];
    for (let i = 0; i < rows; i++) {
        gameState.board[i] = [];
        for (let j = 0; j < cols; j++) {
            gameState.board[i][j] = iconArray[i * cols + j];
        }
    }
}

/**
 * 打乱数组
 */
function shuffleArray(array) {
    const arr = [...array];
    for (let i = arr.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [arr[i], arr[j]] = [arr[j], arr[i]];
    }
    return arr;
}

/**
 * 渲染棋盘
 */
function renderBoard() {
    const { rows, cols } = gameState.config;
    const boardElement = document.getElementById('gameBoard');
    
    boardElement.style.gridTemplateColumns = `repeat(${cols}, 1fr)`;
    boardElement.innerHTML = '';
    
    for (let i = 0; i < rows; i++) {
        for (let j = 0; j < cols; j++) {
            const tile = document.createElement('div');
            tile.className = 'game-tile';
            tile.dataset.row = i;
            tile.dataset.col = j;
            
            const icon = gameState.board[i][j];
            if (icon) {
                tile.textContent = icon;
                tile.onclick = () => handleTileClick(i, j);
            } else {
                tile.classList.add('empty');
            }
            
            boardElement.appendChild(tile);
        }
    }
}

/**
 * 处理棋子点击
 */
function handleTileClick(row, col) {
    if (gameState.isPaused || gameState.isGameOver) return;
    
    const tile = gameState.board[row][col];
    if (!tile) return;
    
    const tileElement = getTileElement(row, col);
    
    // 如果没有选中的棋子
    if (!gameState.selectedTile) {
        gameState.selectedTile = { row, col };
        tileElement.classList.add('selected');
        return;
    }
    
    // 如果点击的是同一个棋子
    if (gameState.selectedTile.row === row && gameState.selectedTile.col === col) {
        tileElement.classList.remove('selected');
        gameState.selectedTile = null;
        return;
    }
    
    // 检查是否可以连接
    const canConnect = checkConnection(gameState.selectedTile, { row, col });
    
    if (canConnect) {
        // 消除棋子
        removePair(gameState.selectedTile, { row, col });
        gameState.selectedTile = null;
        
        // 重置计时器（如果有时间限制）
        if (gameState.config.timeLimit) {
            gameState.timeRemaining = gameState.config.timeLimit;
        }
    } else {
        // 取消之前的选择，选择新的
        const prevElement = getTileElement(gameState.selectedTile.row, gameState.selectedTile.col);
        prevElement.classList.remove('selected');
        gameState.selectedTile = { row, col };
        tileElement.classList.add('selected');
    }
}

/**
 * 检查两个棋子是否可以连接（不超过3条直线）
 */
function checkConnection(tile1, tile2) {
    // 检查是否是相同的图标
    if (gameState.board[tile1.row][tile1.col] !== gameState.board[tile2.row][tile2.col]) {
        return false;
    }
    
    // 检查是否可以通过0条直线连接（相邻）
    if (canConnectDirect(tile1, tile2)) return true;
    
    // 检查是否可以通过1条直线连接
    if (canConnectOneLine(tile1, tile2)) return true;
    
    // 检查是否可以通过2条直线连接
    if (canConnectTwoLines(tile1, tile2)) return true;
    
    // 检查是否可以通过3条直线连接
    if (canConnectThreeLines(tile1, tile2)) return true;
    
    return false;
}

/**
 * 检查是否可以直接连接
 */
function canConnectDirect(tile1, tile2) {
    // 同一行
    if (tile1.row === tile2.row) {
        const minCol = Math.min(tile1.col, tile2.col);
        const maxCol = Math.max(tile1.col, tile2.col);
        for (let col = minCol + 1; col < maxCol; col++) {
            if (gameState.board[tile1.row][col]) return false;
        }
        return true;
    }
    
    // 同一列
    if (tile1.col === tile2.col) {
        const minRow = Math.min(tile1.row, tile2.row);
        const maxRow = Math.max(tile1.row, tile2.row);
        for (let row = minRow + 1; row < maxRow; row++) {
            if (gameState.board[row][tile1.col]) return false;
        }
        return true;
    }
    
    return false;
}

/**
 * 检查是否可以通过一条转折线连接
 */
function canConnectOneLine(tile1, tile2) {
    // 尝试水平-垂直路径
    const corner1 = { row: tile1.row, col: tile2.col };
    if (!gameState.board[corner1.row][corner1.col] || 
        (corner1.row === tile1.row && corner1.col === tile1.col) ||
        (corner1.row === tile2.row && corner1.col === tile2.col)) {
        if (canConnectDirect(tile1, corner1) && canConnectDirect(corner1, tile2)) {
            return true;
        }
    }
    
    // 尝试垂直-水平路径
    const corner2 = { row: tile2.row, col: tile1.col };
    if (!gameState.board[corner2.row][corner2.col] ||
        (corner2.row === tile1.row && corner2.col === tile1.col) ||
        (corner2.row === tile2.row && corner2.col === tile2.col)) {
        if (canConnectDirect(tile1, corner2) && canConnectDirect(corner2, tile2)) {
            return true;
        }
    }
    
    return false;
}

/**
 * 检查是否可以通过两条转折线连接
 */
function canConnectTwoLines(tile1, tile2) {
    const { rows, cols } = gameState.config;
    
    // 尝试所有可能的中间点
    for (let row = 0; row < rows; row++) {
        for (let col = 0; col < cols; col++) {
            if (gameState.board[row][col]) continue;
            
            const middle = { row, col };
            
            // 检查 tile1 -> middle -> tile2
            if (canConnectOneLine(tile1, middle) && canConnectDirect(middle, tile2)) {
                return true;
            }
            
            if (canConnectDirect(tile1, middle) && canConnectOneLine(middle, tile2)) {
                return true;
            }
        }
    }
    
    return false;
}

/**
 * 检查是否可以通过三条转折线连接
 */
function canConnectThreeLines(tile1, tile2) {
    const { rows, cols } = gameState.config;
    
    for (let row = 0; row < rows; row++) {
        for (let col = 0; col < cols; col++) {
            if (gameState.board[row][col]) continue;
            
            const middle = { row, col };
            
            if (canConnectOneLine(tile1, middle) && canConnectOneLine(middle, tile2)) {
                return true;
            }
        }
    }
    
    return false;
}

/**
 * 消除一对棋子
 */
function removePair(tile1, tile2) {
    const element1 = getTileElement(tile1.row, tile1.col);
    const element2 = getTileElement(tile2.row, tile2.col);
    
    // 添加消除动画
    element1.classList.add('matched');
    element2.classList.add('matched');
    
    // 更新棋盘状态
    gameState.board[tile1.row][tile1.col] = null;
    gameState.board[tile2.row][tile2.col] = null;
    
    // 更新统计
    gameState.pairsCleared++;
    gameState.combo++;
    
    if (gameState.combo > gameState.maxCombo) {
        gameState.maxCombo = gameState.combo;
    }
    
    // 计算得分
    const baseScore = gameState.config.baseScore;
    const comboBonus = Math.min(gameState.combo * 6, 108); // 最大连击加分108
    const pairScore = baseScore + comboBonus;
    gameState.score += pairScore;
    
    // 显示连击提示
    if (gameState.combo >= 3) {
        showComboToast(gameState.combo);
    }
    
    // 更新显示
    updateDisplay();
    
    // 延迟后移除元素
    setTimeout(() => {
        element1.classList.add('empty');
        element2.classList.add('empty');
        element1.textContent = '';
        element2.textContent = '';
        element1.onclick = null;
        element2.onclick = null;
        
        // 检查游戏是否结束
        checkGameComplete();
    }, 500);
}

/**
 * 获取棋子DOM元素
 */
function getTileElement(row, col) {
    return document.querySelector(`[data-row="${row}"][data-col="${col}"]`);
}

/**
 * 更新显示
 */
function updateDisplay() {
    document.getElementById('timeDisplay').textContent = gameState.timeRemaining;
    document.getElementById('scoreDisplay').textContent = gameState.score;
    document.getElementById('comboDisplay').textContent = gameState.combo;
    document.getElementById('pairsDisplay').textContent = `${gameState.pairsCleared}/${gameState.totalPairs}`;
    
    // 更新时间标签文字（简单模式显示"已用时间"，其他模式显示"剩余时间"）
    const timeLabel = document.getElementById('timeLabel');
    if (timeLabel && !gameState.config.timeLimit) {
        timeLabel.textContent = '已用时间';
    } else if (timeLabel) {
        timeLabel.textContent = '剩余时间';
    }
    
    // 更新计时器颜色
    const timeDisplay = document.getElementById('timeDisplay');
    timeDisplay.classList.remove('warning', 'danger');
    if (gameState.config.timeLimit) {
        if (gameState.timeRemaining <= 5) {
            timeDisplay.classList.add('danger');
        } else if (gameState.timeRemaining <= 10) {
            timeDisplay.classList.add('warning');
        }
    } else {
        // 简单模式：时间越长越警告（超过5分钟）
        if (gameState.timeRemaining >= 300) {
            timeDisplay.classList.add('warning');
        }
    }
}

/**
 * 启动计时器
 */
function startTimer() {
    if (gameState.timer) {
        clearInterval(gameState.timer);
    }
    
    gameState.timer = setInterval(() => {
        if (gameState.isPaused || gameState.isGameOver) return;
        
        if (gameState.config.timeLimit) {
            // 有时间限制的模式：倒计时
            gameState.timeRemaining--;
            
            if (gameState.timeRemaining <= 0) {
                gameOver(false);
            }
        } else {
            // 无时间限制的模式（简单模式）：正计时
            gameState.timeRemaining++;
        }
        
        updateDisplay();
    }, 1000);
}

/**
 * 检查游戏是否完成
 */
function checkGameComplete() {
    if (gameState.pairsCleared === gameState.totalPairs) {
        gameOver(true);
    } else {
        // 检查是否还有可消除的对子
        if (!hasValidMoves()) {
            // 自动重列
            shuffleBoard();
        }
    }
}

/**
 * 检查是否还有可消除的对子
 */
function hasValidMoves() {
    const { rows, cols } = gameState.config;
    
    for (let i1 = 0; i1 < rows; i1++) {
        for (let j1 = 0; j1 < cols; j1++) {
            if (!gameState.board[i1][j1]) continue;
            
            for (let i2 = 0; i2 < rows; i2++) {
                for (let j2 = 0; j2 < cols; j2++) {
                    if (i1 === i2 && j1 === j2) continue;
                    if (!gameState.board[i2][j2]) continue;
                    
                    if (checkConnection({ row: i1, col: j1 }, { row: i2, col: j2 })) {
                        return true;
                    }
                }
            }
        }
    }
    
    return false;
}

/**
 * 重新排列棋盘
 */
function shuffleBoard() {
    const { rows, cols } = gameState.config;
    let tiles = [];
    
    // 收集所有剩余的棋子
    for (let i = 0; i < rows; i++) {
        for (let j = 0; j < cols; j++) {
            if (gameState.board[i][j]) {
                tiles.push(gameState.board[i][j]);
            }
        }
    }
    
    // 打乱
    tiles = shuffleArray(tiles);
    
    // 重新放置
    let tileIndex = 0;
    for (let i = 0; i < rows; i++) {
        for (let j = 0; j < cols; j++) {
            if (gameState.board[i][j]) {
                gameState.board[i][j] = tiles[tileIndex++];
            }
        }
    }
    
    renderBoard();
}

/**
 * 游戏结束
 */
function gameOver(isWin) {
    gameState.isGameOver = true;
    clearInterval(gameState.timer);
    
    const useTime = Math.floor((Date.now() - gameState.startTime) / 1000);
    
    // 显示结果弹窗
    const modal = document.getElementById('gameModal');
    const modalIcon = document.getElementById('modalIcon');
    const modalTitle = document.getElementById('modalTitle');
    
    if (isWin) {
        modalIcon.textContent = '🎉';
        modalTitle.textContent = '恭喜过关！';
        modalTitle.className = 'modal-title success';
    } else {
        modalIcon.textContent = '😢';
        modalTitle.textContent = '游戏结束';
        modalTitle.className = 'modal-title fail';
    }
    
    document.getElementById('finalScore').textContent = gameState.score;
    document.getElementById('finalCombo').textContent = gameState.maxCombo;
    document.getElementById('finalPairs').textContent = gameState.pairsCleared + '/' + gameState.totalPairs;
    document.getElementById('finalTime').textContent = useTime + '秒';
    
    modal.classList.add('show');
    
    // 保存游戏记录
    saveGameResult(isWin, useTime);
}

/**
 * 保存游戏结果
 */
function saveGameResult(isWin, useTime) {
    const resultData = {
        gameMode: GAME_MODE,
        score: gameState.score,
        maxCombo: gameState.maxCombo,
        pairsCleared: gameState.pairsCleared,
        totalPairs: gameState.totalPairs,
        useTime: useTime,
        result: isWin ? 2 : (gameState.timeRemaining <= 0 ? 3 : 0),
        itemsUsed: JSON.stringify(gameState.itemsUsed)
    };
    
    fetch('/user/game/save', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(resultData)
    })
    .then(response => response.json())
    .then(data => {
        console.log('游戏记录保存成功', data);
    })
    .catch(error => {
        console.error('保存失败', error);
    });
}

/**
 * 显示连击提示
 */
function showComboToast(combo) {
    const toast = document.getElementById('comboToast');
    toast.textContent = `${combo} 连击！`;
    toast.style.display = 'block';
    
    setTimeout(() => {
        toast.style.display = 'none';
    }, 1000);
}

/**
 * 道具代码映射
 */
const TOOL_CODE_MAP = {
    'hint': 'compass',
    'shuffle': 'reshuffle',
    'bomb': 'bomb',
    'freeze': 'freeze'
};

/**
 * 使用道具
 */
function useTool(toolType) {
    if (gameState.isGameOver || gameState.isPaused) return;
    
    const itemCode = TOOL_CODE_MAP[toolType];
    
    // 检查道具数量
    const itemCount = gameState.userItems[itemCode] || 0;
    if (itemCount <= 0) {
        alert('道具数量不足！');
        return;
    }
    
    // 调用后端接口扣除道具
    fetch('/user/game/use-item?itemCode=' + itemCode, {
        method: 'POST'
    })
    .then(response => response.json())
    .then(data => {
        if (data.code === 200) {
            // 更新本地道具数量
            gameState.userItems[itemCode] = data.data;
            updateToolButtons();
            
            // 记录使用
            gameState.itemsUsed.push(itemCode);
            
            // 执行道具效果
            switch (toolType) {
                case 'hint':
                    showHint();
                    break;
                case 'shuffle':
                    shuffleBoard();
                    break;
                case 'bomb':
                    autoRemove();
                    break;
                case 'freeze':
                    addTime();
                    break;
            }
        } else {
            alert(data.message || '使用失败');
        }
    })
    .catch(error => {
        console.error('使用道具失败', error);
        alert('使用失败，请重试');
    });
}

/**
 * 更新道具按钮状态
 */
function updateToolButtons() {
    const toolButtons = document.querySelectorAll('.tool-btn');
    toolButtons.forEach(btn => {
        const onClick = btn.getAttribute('onclick');
        if (onClick) {
            const match = onClick.match(/useTool\('(\w+)'\)/);
            if (match) {
                const toolType = match[1];
                const itemCode = TOOL_CODE_MAP[toolType];
                const count = gameState.userItems[itemCode] || 0;
                
                // 更新按钮文本显示数量
                const textSpan = btn.querySelector('span:last-child');
                if (textSpan) {
                    const originalText = textSpan.textContent.split('(')[0].trim();
                    textSpan.textContent = `${originalText} (${count})`;
                }
                
                // 禁用数量为0的按钮
                if (count <= 0) {
                    btn.disabled = true;
                    btn.style.opacity = '0.5';
                } else {
                    btn.disabled = false;
                    btn.style.opacity = '1';
                }
            }
        }
    });
}

/**
 * 显示提示
 */
function showHint() {
    const { rows, cols } = gameState.config;
    
    for (let i1 = 0; i1 < rows; i1++) {
        for (let j1 = 0; j1 < cols; j1++) {
            if (!gameState.board[i1][j1]) continue;
            
            for (let i2 = i1; i2 < rows; i2++) {
                for (let j2 = (i2 === i1 ? j1 + 1 : 0); j2 < cols; j2++) {
                    if (!gameState.board[i2][j2]) continue;
                    
                    if (checkConnection({ row: i1, col: j1 }, { row: i2, col: j2 })) {
                        const element1 = getTileElement(i1, j1);
                        const element2 = getTileElement(i2, j2);
                        
                        element1.classList.add('hint');
                        element2.classList.add('hint');
                        
                        setTimeout(() => {
                            element1.classList.remove('hint');
                            element2.classList.remove('hint');
                        }, 2000);
                        
                        return;
                    }
                }
            }
        }
    }
}

/**
 * 自动消除一对
 */
function autoRemove() {
    const { rows, cols } = gameState.config;
    
    for (let i1 = 0; i1 < rows; i1++) {
        for (let j1 = 0; j1 < cols; j1++) {
            if (!gameState.board[i1][j1]) continue;
            
            for (let i2 = i1; i2 < rows; i2++) {
                for (let j2 = (i2 === i1 ? j1 + 1 : 0); j2 < cols; j2++) {
                    if (!gameState.board[i2][j2]) continue;
                    
                    if (checkConnection({ row: i1, col: j1 }, { row: i2, col: j2 })) {
                        removePair({ row: i1, col: j1 }, { row: i2, col: j2 });
                        return;
                    }
                }
            }
        }
    }
}

/**
 * 增加时间
 */
function addTime() {
    if (gameState.config.timeLimit) {
        gameState.timeRemaining += 10;
        updateDisplay();
    }
}

/**
 * 暂停游戏
 */
function pauseGame() {
    gameState.isPaused = !gameState.isPaused;
    const btn = event.target;
    btn.textContent = gameState.isPaused ? '▶️ 继续' : '⏸️ 暂停';
}

/**
 * 重新开始
 */
function restartGame() {
    document.getElementById('gameModal').classList.remove('show');
    clearInterval(gameState.timer);
    initGame();
}

/**
 * 退出游戏
 */
function quitGame() {
    if (confirm('确定要退出游戏吗？')) {
        window.location.href = '/user/game/select';
    }
}

/**
 * 返回选择
 */
function backToSelect() {
    window.location.href = '/user/game/select';
}

// 页面加载完成后初始化游戏
window.addEventListener('DOMContentLoaded', function() {
    initGame();
});

